package com.nus.servlets;

import com.nus.beans.User;
import com.nus.database.UserDBManager;
import com.nus.services.EncodingService;
import com.nus.services.ValidationService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/29/12
 * Time: 12:14 AM
 * To change this template use File | Settings | File Templates.
 */
public class ChangePasswordServlet extends AbstractServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        String currentPassword = request.getParameter("currentPassword");

        ValidationService validationService = new ValidationService();
        String errorMessage = null;

        User user = (User) request.getSession().getAttribute("user");
        EncodingService encodingService = new EncodingService();

        String encodedNewPassword = encodingService.encode(password1);
        String encodedExistingPassword = encodingService.encode(currentPassword);

        String targetPage = "/WEB-INF/update_password.jsp";

        if (validationService.isEmpty(password1)) {
            errorMessage = "Password one should not be empty";
        } else if (validationService.isEmpty(password2)) {
            errorMessage = "Password two should not be empty";
        } else if (!password1.equals(password2)) {
            errorMessage = "Both passwords should be equal";
        } else if(!encodedExistingPassword.equals(user.getPassword())){
            errorMessage = "Current password is not correct";
        } else {

            Connection connection = getUserDatabaseConnection(request);
            UserDBManager userDBManager = new UserDBManager(connection);
            userDBManager.updatePassword(encodedNewPassword, user);
            targetPage = "logout.do";
            userDBManager.close();
        }
        request.setAttribute("ERROR_MESSAGE", errorMessage);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(targetPage);
        requestDispatcher.forward(request, response);
    }
}
